package com.ponhu.ea2.goodsCenter.provider.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.google.common.collect.Lists;
import com.ponhu.ea2.constants.CommonConstant;
import com.ponhu.ea2.entity.PhCategory;
import com.ponhu.ea2.entity.PhCategoryPropertyMd;
import com.ponhu.ea2.entity.PhProperty;
import com.ponhu.ea2.goodsCenter.provider.mapper.PhPropertyMapper;
import com.ponhu.ea2.goodsCenter.provider.service.PhCategoryPropertyMdService;
import com.ponhu.ea2.goodsCenter.provider.service.PhCategoryService;
import com.ponhu.ea2.goodsCenter.provider.service.PhPropertyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 属性表  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-10-19
 */
@Service
public class PhPropertyServiceImpl
        extends ServiceImpl<PhPropertyMapper, PhProperty>
        implements PhPropertyService {

    @Autowired
    private PhCategoryPropertyMdService phCategoryPropertyMdService;
    @Autowired
    private PhCategoryService phCategoryService;

    /**
     * 根据类目ID查询当前类目及其所有上级类目的所有属性
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<PhProperty> getPropertyByCategoryId(Long categoryId, Integer level) {

        List<Long> categoryIds = Lists.newArrayList();
        if (level == CommonConstant.CATEGORY_LEVEL_1) {
            categoryIds.add(categoryId);
        }
        if (level == CommonConstant.CATEGORY_LEVEL_2) {
            categoryIds.add(categoryId);
            categoryIds.add(phCategoryService.getById(categoryId).getId());
        }
        if (level == CommonConstant.CATEGORY_LEVEL_3) {
            categoryIds.add(categoryId);
            PhCategory level3 = phCategoryService.getById(categoryId);
            categoryIds.add(level3.getParentId());
            PhCategory level2 = phCategoryService.getById(level3.getParentId());
            categoryIds.add(level2.getParentId());
        }
        if (CollectionUtils.isEmpty(categoryIds)) return Lists.newArrayList();

        List<Long> propertyIds = phCategoryPropertyMdService.getCategoryPropertyByCids(categoryIds)
                .stream().map(PhCategoryPropertyMd::getPropertyId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(propertyIds)) return Lists.newArrayList();

        return listByIds(propertyIds);
    }

}
